package com.java.escape.computeAndListOrInterface;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName NumberAndDate
 * @Description BigDecimal and SimpleDateFormat 精度问题
 * @Author wyp
 * @Date 2023/8/23 14:22
 * @Version 1.0
 */
@SuppressWarnings("all")
public class NumberAndDate {

    public static void main(String[] args) throws ParseException {
        BigDecimal one = new BigDecimal(22.865);
        //BigDecimal two=one.setScale(2);//精度丢失 problem:给定数字精度与设置不一致
        // System.out.println(two);
        BigDecimal three = one.setScale(2, RoundingMode.UP);
        System.out.println(three);

        BigDecimal four = new BigDecimal("13.677");
        //BigDecimal five = four.divide(one);//除法不尽 problem:无线循环导致异常
        BigDecimal reslut = four.divide(one, 2, RoundingMode.UP);
        System.out.println(reslut);

        //BigDecimal 精度比较使用compareTo而不是equals方法:
        //equals: 0!=0.00
        // compareTo: 0=0.00


//        DateTimeSafety();

        threadUnSafety();
    }

    /**
     * SimpleDateFormat 只能解析精度大于或等于给定的pattern
     * 存在线程安全问题 解决方法:1.改为局部变量 2.ThreadLocal 3.synchronized锁机制（降低性能）
     *
     * @throws ParseException
     */
    public static void DateTimeSafety() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.applyLocalizedPattern("yyyy-MM-dd HH:mm:ss");
        String date = "2023-08-23 14:46:00";
        String date1 = "2023-08";
        System.out.println(sdf.parse(date));
        System.out.println(sdf.parse(date1));
    }

    public static void threadUnSafety() {
        ThreadPoolExecutor the = new ThreadPoolExecutor(
                10, 100, 1, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(1000)
        );
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //多线程安全问题 DateFormat 里面的Calendar为全局变量不安全导致
        while (true) {
            the.execute(() -> {
                try {
                    Date date = sdf.parse("2022-03-12 22:22:11");
                    String format = sdf.format(date);
                    System.out.println(format.equals("2022-03-12 22:22:11"));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            });
        }
    }

}
